package cn.zcscloud.mall.service.impl;

import cn.zcscloud.mall.common.CustomException;
import cn.zcscloud.mall.dto.UmsMenuNode;
import cn.zcscloud.mall.mbg.mapper.UmsMenuMapper;
import cn.zcscloud.mall.mbg.model.UmsMenu;
import cn.zcscloud.mall.mbg.model.UmsRoleMenuRelation;
import cn.zcscloud.mall.service.UmsMenuService;
import cn.zcscloud.mall.service.UmsRoleMenuRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UmsMenuServiceImpl extends ServiceImpl<UmsMenuMapper, UmsMenu> implements UmsMenuService {
    @Autowired
    private UmsRoleMenuRelationService umsRoleMenuRelationService;

    /**
     * 树形结构返回所有菜单列表
     *
     * @return
     */
    @Override
    public List<UmsMenuNode> treeList() throws InvocationTargetException, IllegalAccessException {
        ArrayList<UmsMenuNode> list = new ArrayList<>();
        // 获取一级菜单
        LambdaQueryWrapper<UmsMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsMenu::getLevel, 0);
        List<UmsMenu> umsMenus = this.list(queryWrapper);
        //遍历一级菜单获取对应二级菜单
        for (UmsMenu umsMenu : umsMenus) {
            UmsMenuNode umsMenuNode = new UmsMenuNode();
            LambdaQueryWrapper<UmsMenu> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UmsMenu::getParentId, umsMenu.getId());
            List<UmsMenu> children = this.list(wrapper);
            //封装对象
            BeanUtils.copyProperties(umsMenu, umsMenuNode);
            umsMenuNode.setChildren(children);
            list.add(umsMenuNode);
        }
        return list;
    }

    @Override
    public void deleteById(Integer id) {
        //如果要删除的菜单包含子菜单，那么将不能删除
        LambdaQueryWrapper<UmsMenu> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(UmsMenu::getParentId, id);
        //如果要删除的菜单和角色产生了关联，那么将不能删除
        LambdaQueryWrapper<UmsRoleMenuRelation> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(UmsRoleMenuRelation::getMenuId, id);
        if (this.count(lqw1) > 0 || umsRoleMenuRelationService.count(lqw2) > 0) {
            throw new CustomException("当前菜单下有子菜单或关联了角色，不能删除");
        }
        this.removeById(id);
    }
}
